package com.jy.oms.framework.asyn.task.alarm;

import com.jy.oms.framework.asyn.task.core.ExecutorContext;
import com.jy.oms.framework.asyn.task.handler.ITaskHandlerProcessor;
import com.jy.oms.framework.util.SpringUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 告警服务
 *
 * @author liuquan
 */
@Service
public class AlarmMessageFacade implements ITaskAlarmMessageService, ITaskHandlerProcessor {
    private static Logger logger = LoggerFactory.getLogger(AlarmMessageFacade.class);

    private List<ITaskAlarmMessageService> alarmMessageServiceList;

    public AlarmMessageFacade(List<ITaskAlarmMessageService> alarmMessageServices) {
        this.alarmMessageServiceList = alarmMessageServices.stream()
                .filter(service -> !(service instanceof TaskErrorAlarmMessageService))
                .collect(Collectors.toList());
    }

    @Override
    public void processAfterTaskHandlerInitialization() {
        if (!ExecutorContext.isAbleAlarm()) {
            return;
        }

        if(CollectionUtils.size(this.alarmMessageServiceList) > 0){
            return;
        }

        logger.warn("\r\n" +
                    "-----------------------------------------\r\n" +
                    "-----------------------------------------\r\n" +
                    "没有配置任务告警服务，容易丢失任务出错信息，\r\n" +
                    "可定义@Bean[WechatAlarmMessageService]，  \r\n" +
                    "或自定义一个或多个告警服务，实现接口[ITaskAlarmMessageService]  \r\n" +
                    "----------------------------------------- \r\n" +
                    "-----------------------------------------");
    }

    @Override
    public void alarm(AlarmMessage alarmMessage) {
        if (alarmMessage == null) {
            return;
        }

        if (CollectionUtils.isEmpty(this.alarmMessageServiceList)) {
            return;
        }

        if (!ExecutorContext.isAbleAlarm()) {
            return;
        }

        for (ITaskAlarmMessageService alarmMessageService : this.alarmMessageServiceList) {
            try {
                alarmMessageService.alarm(alarmMessage);
            } catch (Exception e){
                logger.error("任务告警报错", e);
            }
        }
    }

    public static AlarmMessageFacade getInstance() {
        return SpringUtil.getBean(AlarmMessageFacade.class);
    }

}
